<template>

  <div class="index-body">
    <el-row :gutter="20" style="margin-top: 100px">
      <el-col :span="24">
        <el-row style="position: relative; top: 30px">
          <el-col span="5" offset="19">
            <el-input
              v-model="queryinfo.query"
              size="large"
              placeholder="输入商品名搜索"
            >
              <el-button
                type="primary"
                @click="clickSearch"
                icon="el-icon-search"
                slot="append"
                v-loading.fullscreen.lock="fullscreenLoading"
              ></el-button
            ></el-input>
          </el-col>
        </el-row>

       

          <p class="index-body-p-1" style="margin-top: 60px">
            {{ goodCategory }}
          </p>
          <hr />
          <el-row
            style="margin-top: 50px"
            v-for="(obj1, index1) in getRowNums(index)"
            :key="index1"
          >
            <el-col
              :span="4"
              v-for="(obj2, index2) in mySlice(
                goodList,
                index1 * 4,
                (index1 + 1) * 4
              )"
              :key="index2"
              :offset="index2 > 0 ? 2 : 1"
            >
              <el-card :body-style="{ padding: '0px', textAlign: 'center' }">
                <img
                  :src="obj2.imageUrlList[0]"
                  class="image"
                  style="width: 100%"
                  alt="请检查网络连接"
                />
                <div style="padding: 10px">
                  <h4>{{ obj2.goodName }}</h4>
                  <div class="bottom clearfix">
                    <el-button
                      type="text"
                      class="button"
                      @click="clickGoodsInfoButton(obj2.goodId)"
                      >查看详情</el-button
                    >
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
           <!--        分页组件-->
        <el-row
          style="text-align: center; margin-top: 80px"
        >
          <el-col :span="24">
            <!--限定每页 12 条数据-->
            <el-pagination
              background
              @current-change="handleCurrentChange"
              :current-page.sync="queryinfo.pageNum"
              :page-size="queryinfo.pageSize"
              layout="prev, pager, next, jumper"
              :total="total">
            </el-pagination>
          </el-col>
        </el-row>
      </el-col>
    </el-row>

    <!--      商品详情弹出框-->
    <el-dialog :visible.sync="centerDialogVisible" width="418px" center>
      <div style="text-align: center">
        <el-carousel direction="horizontal" :autoplay="true">
          <el-carousel-item
            v-for="(v, k) in goodInfo.imageUrlList"
            :key="k"
            style="width: 365px; height: 250px"
          >
            <img :src="v" alt="请检查网络连接" width="93%" />
          </el-carousel-item>
        </el-carousel>
        <h3 style="text-align: left">￥：{{ goodInfo.goodPrice }}</h3>
        <p style="text-align: left; font-weight: bold; font-size: 18px">
          {{ goodInfo.goodName }}
        </p>
        <p style="text-align: left">描述：{{ goodInfo.goodDescription }}</p>
        <p style="text-align: left">校区：{{ goodInfo.goodAddress }}</p>
        <p style="text-align: left">交易方式：{{ goodInfo.transactionMode }}</p>

        <span slot="footer" class="dialog-footer">
          <el-button
            v-if="!goodInfo.inMyWant"
            type="success"
            @click="addToShopCar"
            style="margin-top: 30px"
            > ♥ 我想要 ♥</el-button>
          <el-button
            type="primary"
            v-if="goodInfo.inMyWant"
            :disabled="goodInfo.inMyWant"
            @click="addToShopCar"
            style="margin-top: 30px"
            > ♥ 我想要 ♥</el-button>
        </span>
      </div>
    </el-dialog>

    <!--      加入购物车结果提示框-->
    <el-dialog
      title="提示"
      :visible.sync="centerDialogVisible2"
      width="30%"
      center
    >
      <div style="text-align: center">
        <h4>{{ dialogValue }}</h4>
        <span slot="footer" class="dialog-footer">
          <el-row style="margin-top: 30px">
            <el-col :span="6" :offset="5">
              <el-button type="primary" @click="clickButton" style="width: 100%"
                >确 定</el-button
              >
            </el-col>
            <el-col :span="6" :offset="2">
              <el-button
                type="primary"
                @click="clickGoToShopCar"
                :disabled="goToShopCar"
                >前往“我想要”</el-button
              >
            </el-col>
          </el-row>
        </span>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "index-category",
  props: ['goodCategoryId', 'goodCategory'],
  data() {
    return {
      rules: {
        search: [{ validator: checkString, trigger: "blur" }],
      },
      queryinfo: {
        pageNum: 1,
        pageSize: 8,
        query: "",
        userId: "",
      },
      total: 0,
      goodCategoryList: [],
      search: "",
      dataSearch: [], //用来保存搜索的全部结果
      branchData:[],
      goodInfo: [],
      goodsInfoId: "",
      goodsInfoImg: {},
      goodsInfoName: "",
      goodsInfoDscrip: "",
      goodsInfoPrice: 0,
      centerDialogVisible: false,
      dialogValue: "",
      centerDialogVisible2: false,
      goToShopCar: true,
      currentPage: 1, //初始页
      pageSize: 8, //每页的数据
      paginationShow: false, //默认不显示分页
      goodList: []
    };
    let checkString = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请填写内容"));
      } else {
        callback();
      }
    };
  },
  created() {
    this.getGoodList()
  },
  watch: {
    $route(){
        this.getGoodList()
    },
  },
  methods: {
    getGoodList() {
      let self = this;
      let jsonObj = {};
      jsonObj.goodCategoryId = self.goodCategoryId;
      jsonObj.pageNum = self.queryinfo.pageNum;
      jsonObj.pageSize = self.queryinfo.pageSize;
      jsonObj.query = self.queryinfo.query;
      jsonObj.userId = window.sessionStorage.getItem("userId");
      $.get(
        "http://waiterxiaoyy.free.idcfengye.com/web/getgoodslist",
        jsonObj,
        function (data) {
          self.goodList = data.data;
          self.total = data.count;
          // console.log('类型', self.goodCategoryList);
        },
        "json"
      );
    },
    //点击查看详情
    clickGoodsInfoButton(goodId) {
      this.centerDialogVisible = true;
      this.goodsInfoId = goodId;
      let self = this;
      let jsonObj = {};
      jsonObj.goodId = goodId;
      jsonObj.userId = window.sessionStorage.getItem("userId");
      $.get(
        "http://waiterxiaoyy.free.idcfengye.com/web/getgoodbygoodid",
        jsonObj,
        function (data) {
          self.goodInfo = data.data[0];
        },
        "json"
      );
    },
    addToShopCar() {
      let jsonObj = {};
      jsonObj.userId = window.sessionStorage.getItem("userId");
      jsonObj.goodId = this.goodsInfoId;
      let jsonMsg = JSON.stringify(jsonObj);
      let self = this;
      $.post(
        "http://waiterxiaoyy.free.idcfengye.com/web/addiwant",
        jsonMsg,
        function (data) {
          if (data.code === 200) {
            self.dialogValue = data.msg;
            self.goToShopCar = false;
          } else {
            self.dialogValue = data.msg;
            self.goToShopCar = true;
          }
        },
        "json"
      );
      self.centerDialogVisible2 = true;
    },
    // 获取长度为len的随机字符串
    getRandomString(len) {
      len = len || 32;
      let $chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678";
      let maxPos = $chars.length;
      let pwd = "";
      for (let i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
      }
      return pwd;
    },
    clickButton() {
      this.centerDialogVisible = false;
      this.centerDialogVisible2 = false;
    },
    //点击跳转购物车按钮
    clickGoToShopCar() {
      this.clickButton();
      this.$router.push("shopCar");
    },
    // 初始页currentPage、初始每页数据数pageSize和数据data
    // 点击了分页组件换页按钮
    handleCurrentChange(currentPage) {
      this.queryinfo.pageNum = currentPage;
      this.getGoodList()
    },
    //点击搜索按钮
    clickSearch() {
      this.getGoodList()
    },
    //计算打印的行数
    getRowNums(index) {
      let data = this.goodList;
      // console.log('数据3', data)
      let len = parseInt(data.length / 4);
      if (len === 0) {
        return 1;
      } else {
        if (data.length - len * 4 > 0) {
          return len + 1;
        } else {
          return len;
        }
      }
    },
    getRow(index) {
      let data = this.goodList;
      let arr = [];
      let row = Math.ceil(data / 5);
      //  行循环
      for (let i = 0; i < row; i++) {
        //  第i行的商品
        arr[i] = [];
        // modLast：最后一行的商品个数
        let modLast =
          data.length % 5 === 0 ? 5 : data % 5;
        // lastRow：判断当前循环是不是最后一行，是就让内层循环最后一行的商品个数，不是则默认5个
        let lastRow = i === row - 1 ? modLast : 5;
        //  列循环
        for (let j = 0; j < lastRow; j++) {
          arr[i][j] = data[5 * i + j];
        }
      }
      //  最后得到arr数组，将数组赋值给一个变量
      this.branchData = arr;
    },
    //数组切割
    mySlice(data, indexStart, indexEnd) {
      if (indexStart < 0) indexStart = 0;
      if (data.length >= indexEnd) {
        return data.slice(indexStart, indexEnd);
      } else {
        if (indexStart < data.length) {
          return data.slice(indexStart, data.length);
        } else {
          return [];
        }
      }
    },
  },
};
</script>

<style scoped>
.index-body {
  width: 80%;
  margin: 0 auto;
  border-radius: 3.125rem;
}
.index-body-p-1 {
  font-weight: bold;
  font-size: 30px;
  color: black;
  margin-top: 30px;
  border-radius: 3.125rem;
}
.el-carousel {
  border-radius: 3.125rem;
  width: 100%;
}
</style>
